import cv2
import numpy as np
import time
import requests
from urllib.parse import quote
import os
from datetime import datetime
import socket
import subprocess


IMG_PATH = None

def get_wifi_ssid():
    try:
        # 获取当前连接的WiFi SSID
        output = subprocess.check_output(['netsh', 'wlan', 'show', 'interfaces']).decode('gbk')
        for line in output.split('\n'):
            if 'SSID' in line and 'BSSID' not in line:
                return line.split(':')[1].strip()
    except:
        return None
    return None


def check_same_network(camera_ip):
    try:
        # 获取本地IP地址的前三个段
        hostname = socket.gethostname()
        local_ip = socket.gethostbyname(hostname)
        local_network = '.'.join(local_ip.split('.')[:3])

        # 获取摄像头IP地址的前三个段
        camera_network = '.'.join(camera_ip.split('.')[:3])

        return local_network == camera_network
    except:
        return False


def test_camera_connection(camera_ip, camera_port, username, password):
    # 测试不同的URL格式
    urls = [
        f"http://{camera_ip}:{camera_port}/video",
        f"http://{camera_ip}:{camera_port}/stream",
        f"http://{camera_ip}:{camera_port}/mjpg/video.mjpg",
        f"http://{camera_ip}:{camera_port}/snapshot.cgi",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/video",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/stream",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/mjpg/video.mjpg",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/snapshot.cgi",
        # 添加更多可能的URL格式
        f"http://{camera_ip}:{camera_port}/live",
        f"http://{camera_ip}:{camera_port}/live/ch00_0.h264",
        f"http://{camera_ip}:{camera_port}/live/ch00_1.h264",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/live",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/live/ch00_0.h264",
        f"http://{username}:{password}@{camera_ip}:{camera_port}/live/ch00_1.h264"
    ]

    print("正在测试摄像头连接...")
    for url in urls:
        try:
            print(f"尝试连接: {url}")
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                print(f"成功连接到: {url}")
                return url
        except requests.exceptions.RequestException as e:
            print(f"连接失败: {str(e)}")
    return None


def save_image(frame, save_dir, filename="default.jpg"):
    try:
        # 确保保存目录存在
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        filepath = os.path.join(save_dir, filename)
        print(f"保存照片到: {filepath}")

        # 确保frame是有效的图像数据
        if frame is None or frame.size == 0:
            print("无效的图像数据")
            return False

        # 检测二维码
        qr_detector = cv2.QRCodeDetector()
        retval, points = qr_detector.detect(frame)
        if retval:  # 如果检测到二维码
            print("6090")

        # 保存图片
        success = cv2.imwrite(filepath, frame)
        if success:
            print(f"照片已更新: {filepath}")
            return True
        else:
            print("保存照片失败")
            return False
    except Exception as e:
        print(f"保存照片时出错: {str(e)}")
        return False

save_dir = "D:/embedded/ZhiNengDaoChang_TJ/src/assets/camera"
def camera_executor(camera_thread):
    # 摄像头参数
    camera_ip = "192.168.11.2"
    camera_port = "81"
    username = "admin"
    password = "888888"

    global save_dir
    print(f"启动画面捕捉 {save_dir}")

    # 获取当前WiFi SSID
    current_ssid = get_wifi_ssid()
    if current_ssid:
        print(f"当前连接的WiFi: {current_ssid}")
    else:
        print("无法获取当前WiFi信息")

    # 测试摄像头连接
    working_url = test_camera_connection(camera_ip, camera_port, username, password)

    if not working_url:
        print("无法找到可用的视频流URL，请检查以下内容：")
        print("1. 确保摄像头已正确连接到网络")
        print("2. 确保电脑和摄像头在同一个网络中")
        print("3. 尝试ping摄像头IP地址")
        print("4. 检查摄像头的用户名和密码是否正确")
        print("5. 检查摄像头的HTTP端口是否正确")
        return

    print(f"使用URL: {working_url}")

    # 创建视频捕获对象
    cap = cv2.VideoCapture(working_url)

    if not cap.isOpened():
        print("无法打开视频流，请检查摄像头状态")
        return

    # 设置视频捕获参数
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    cap.set(cv2.CAP_PROP_FPS, 30)

    print("成功连接到摄像头，开始保存照片...")
    print("程序将每3秒更新一次照片")
    print("按Ctrl+C退出程序")

    frame_count = 0
    last_save_time = time.time()
    save_interval = 5  # 保存间隔（秒）

    try:
        while True:
            # 读取视频帧
            ret, frame = cap.read()
            if not ret:
                print("无法获取视频帧，尝试重新连接...")
                cap.release()
                time.sleep(1)
                cap = cv2.VideoCapture(working_url)
                continue

            current_time = time.time()
            print("-------------------")

            # 检查是否需要保存照片（定时保存）
            if current_time - last_save_time >= save_interval:
                status = save_image(frame, save_dir)  # 使用默认文件名，覆盖旧照片
                if status:
                    last_save_time = current_time
                    print(f"距离下次更新还有 {save_interval} 秒")

            # 每30帧检查一次连接状态
            frame_count += 1
            if frame_count >= 30:
                frame_count = 0
                if not cap.isOpened():
                    print("连接断开，尝试重新连接...")
                    cap.release()
                    time.sleep(1)
                    cap = cv2.VideoCapture(working_url)

            # 短暂延时，避免CPU占用过高
            time.sleep(0.1)

    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        # 释放资源
        cap.release()
